﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using LDSCore;
using LDSModel;
using LDSModel.Dal;
using LDSProject.Properties;

namespace LDSProject.Forms
{
    public partial class DeviceForm : Form
    {
        Data_Device _device;
        FormState _formState;
        bool _isSelectOilTank;

        public DeviceForm(Guid deviceId)
        {
            InitializeComponent();

            _device = DeviceService.Instance.GetDevice(deviceId);
        }

        private void DeviceForm_Load(object sender, EventArgs e)
        {
            dateTimePicker1.Value = DateTime.Now.Date;
            dateTimePicker2.Value = DateTime.Now;

            //dateTimePicker1.MaxDate = DateTime.Now;
            //dateTimePicker2.MaxDate = DateTime.Now;

            cbOilTank.DataSource = DeviceService.Instance.OilTankList;
            cbOilTank.SelectedIndex = -1;

            var bs = new BindingSource { DataSource = ChartQueryType.Now.ToList() };
            cbQueryType.DataSource = bs;
            cbQueryType.ValueMember = "Key";
            cbQueryType.DisplayMember = "Value";

            _formState = FormState.Loading;

            var first = DeviceService.Instance.OilTankList.FirstOrDefault(d => d.OId == _device.OID);
            if (first != null) cbOilTank.SelectedIndex = cbOilTank.Items.IndexOf(first);

            if (UserService.CurrentUser.IsManager != null) lbSetAlarm.Visible = UserService.CurrentUser.IsManager.Value;

            RefushAlarm();

            _formState = FormState.Loaded;

            btnQuery.PerformClick();
        }

        private void Button_MouseEnter(object sender, EventArgs e)
        {
            var button = (Button)sender;
            button.BackgroundImage = Resources.BtnBackOn;
        }

        private void Button_MouseLeave(object sender, EventArgs e)
        {
            var button = (Button)sender;
            button.BackgroundImage = Resources.BtnBack;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            var saveFileDialog1 = new SaveFileDialog
                {
                    Filter =
                        @"Bitmap (*.bmp)|*.bmp|JPEG (*.jpg)|*.jpg|EMF (*.emf)|*.emf|PNG (*.png)|*.png|GIF (*.gif)|*.gif|TIFF (*.tif)|*.tif",
                    FilterIndex = 2,
                    RestoreDirectory = true
                };

            // Sets the current file name filter string, which determines 
            // the choices that appear in the "Save as file type" or 
            // "Files of type" box in the dialog box.

            // Set image file format
            if (saveFileDialog1.ShowDialog() != DialogResult.OK) return;
            var format = ChartImageFormat.Bmp;

            if (saveFileDialog1.FileName.EndsWith("bmp"))
            {
                format = ChartImageFormat.Bmp;
            }
            else if (saveFileDialog1.FileName.EndsWith("jpg"))
            {
                format = ChartImageFormat.Jpeg;
            }
            else if (saveFileDialog1.FileName.EndsWith("emf"))
            {
                format = ChartImageFormat.Emf;
            }
            else if (saveFileDialog1.FileName.EndsWith("gif"))
            {
                format = ChartImageFormat.Gif;
            }
            else if (saveFileDialog1.FileName.EndsWith("png"))
            {
                format = ChartImageFormat.Png;
            }
            else if (saveFileDialog1.FileName.EndsWith("tif"))
            {
                format = ChartImageFormat.Tiff;
            }

            // Save image
            chartControl1.chart1.SaveImage(saveFileDialog1.FileName, format);
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            var dialog = new PrintForm(chartControl1);
            dialog.ShowDialog(this);
        }

        private void cbOilTank_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (_formState == FormState.None) return;

                _isSelectOilTank = true;

                var list = DeviceService.Instance.LoadDeviceList((Guid)cbOilTank.SelectedValue);
                cbDevice.DataSource = list;

                _isSelectOilTank = false;

                switch (_formState)
                {
                    case FormState.Loading:
                        {
                            if (list != null)
                            {
                                var first = list.FirstOrDefault(d => d.DeviceId == _device.DeviceId);
                                if (first != null) cbDevice.SelectedIndex = cbDevice.Items.IndexOf(first);
                            }
                        }
                        break;
                    case FormState.Loaded:
                        {
                            cbDevice.SelectedIndex = -1;
                        }
                        break;
                }
            }
            catch (Exception ex)
            {
                LogFileHelper.Record(ex);
            }
        }

        private void btnQueryConfig_Click(object sender, EventArgs e)
        {
            try
            {
                if (!MainConsole.Instance.CheckPortIsOpen(this)) return;
                var returnInfo = new StringBuilder();
                const MsgType type = MsgType.ZGCMD_READ_SYSINFO;
                if (_device.Address != null)
                {
                    var addressList = new List<int> { _device.Address.Value };
                    var dialog = new CmdProcessForm(new List<int>(addressList), type, null, ref returnInfo);
                    dialog.ShowDialog(this);
                }
                lbInfo.Text = returnInfo.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnQueryData_Click(object sender, EventArgs e)
        {
            var dialog = new QueryForm(_device.DeviceId);
            dialog.ShowDialog(this);
        }

        private void btnGetTime_Click(object sender, EventArgs e)
        {
            try
            {
                if (!MainConsole.Instance.CheckPortIsOpen(this)) return;
                var returnInfo = new StringBuilder();
                const MsgType type = MsgType.ZGCMD_READ_SYSTIME;
                if (_device.Address != null)
                {
                    var addressList = new List<int> { _device.Address.Value };
                    var dialog = new CmdProcessForm(new List<int>(addressList), type, null, ref returnInfo);
                    dialog.ShowDialog(this);
                }
                lbInfo.Text = returnInfo.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSyanTime_Click(object sender, EventArgs e)
        {
            try
            {
                if (!MainConsole.Instance.CheckPortIsOpen(this)) return;
                const MsgType type = MsgType.ZGCMD_SET_SYSTIME;
                var result = MessageBox.Show(this, @"是否确认" + type.Description() + @"?", @"提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result != DialogResult.Yes) return;
                var returnInfo = new StringBuilder();
                if (_device.Address != null)
                {
                    var addressList = new List<int> { _device.Address.Value };
                    var dialog = new CmdProcessForm(new List<int>(addressList), type, null, ref returnInfo);
                    dialog.ShowDialog(this);
                }
                lbInfo.Text = returnInfo.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            try
            {
                if (!MainConsole.Instance.CheckPortIsOpen(this)) return;
                const MsgType type = MsgType.ZGCMD_RESET;
                var result = MessageBox.Show(this, @"是否确认" + type.Description() + @"?", @"提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result != DialogResult.Yes) return;
                var returnInfo = new StringBuilder();
                if (_device.Address != null)
                {
                    var addressList = new List<int> { _device.Address.Value };
                    var dialog = new CmdProcessForm(new List<int>(addressList), type, null, ref returnInfo);
                    dialog.ShowDialog(this);
                }
                lbInfo.Text = returnInfo.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnRestore_Click(object sender, EventArgs e)
        {
            try
            {
                if (!MainConsole.Instance.CheckPortIsOpen(this)) return;
                const MsgType type = MsgType.ZGCMD_DEFAULT;
                var result = MessageBox.Show(this, @"是否确认" + type.Description() + @"?", @"提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                if (result != DialogResult.Yes) return;
                var returnInfo = new StringBuilder();
                if (_device.Address != null)
                {
                    var addressList = new List<int> { _device.Address.Value };
                    var dialog = new CmdProcessForm(new List<int>(addressList), type, null, ref returnInfo);
                    dialog.ShowDialog(this);
                }
                lbInfo.Text = returnInfo.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            try
            {
                if (_isSelectOilTank || cbDevice.SelectedIndex < 0) return;
                Text = string.Format("{0}-{1} {2}", cbOilTank.Text, cbDevice.Text, cbQueryType.Text);

                _device = DeviceService.Instance.GetDevice((Guid)cbDevice.SelectedValue);

                RefushAlarm();

                chartControl1.ReLoad(_device.DeviceId, (ChartQueryType)cbQueryType.SelectedValue, dateTimePicker1.Value, dateTimePicker2.Value);
            }
            catch (Exception ex)
            {
                LogFileHelper.Record(ex);
            }
        }

        private void cbQueryType_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch ((ChartQueryType)cbQueryType.SelectedIndex)
            {
                case ChartQueryType.Now:
                    {
                        label2.Visible = false;
                        label3.Visible = false;
                        dateTimePicker1.Visible = false;
                        dateTimePicker2.Visible = false;
                    }
                    break;
                case ChartQueryType.History:
                    {
                        label2.Visible = true;
                        label3.Visible = true;
                        dateTimePicker1.Visible = true;
                        dateTimePicker2.Visible = true;
                        dateTimePicker2.Value = DateTime.Now;
                    }
                    break;
            }
        }

        private void DeviceForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            chartControl1.Dispose();
        }

        private void lbSetAlarm_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var dialog = new AlermMaxValueSetForm(_device.DeviceId);
            if (DialogResult.OK == dialog.ShowDialog(this))
            {
                RefushAlarm();
            }
        }

        void RefushAlarm()
        {
            lbAlarm.Text = string.Format("阀值: {0} kA", DeviceService.Instance.GetAlermValue(_device.DeviceId));
        }
    }
}
